package cn.iocoder.yudao.module.jikong.controller.app.user;

import cn.hutool.core.io.IoUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.erp.controller.app.auth.vo.*;
import cn.iocoder.yudao.module.erp.controller.app.erpSupplier.vo.ErpSupplierInfoRespVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpSupplierDO;
import cn.iocoder.yudao.module.erp.service.AppCaptchaService;
import cn.iocoder.yudao.module.infra.controller.app.file.vo.AppFileUploadReqVO;
import cn.iocoder.yudao.module.infra.service.file.FileService;
import cn.iocoder.yudao.module.jikong.controller.admin.user.vo.UserRespVO;
import cn.iocoder.yudao.module.jikong.controller.admin.user.vo.UserSaveReqVO;
import cn.iocoder.yudao.module.jikong.controller.app.user.vo.*;
import cn.iocoder.yudao.module.jikong.dal.dataobject.user.JkUserDO;
import cn.iocoder.yudao.module.jikong.service.user.JkUserService;
import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeUseReqDTO;
import cn.iocoder.yudao.module.system.enums.sms.SmsSceneEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "WEB用户登录相关接口")
@RestController
@RequestMapping("/jikong/auth")
@Validated
public class JkAppUserController {

    @Resource
    private JkUserService jkUserService;

    @Autowired
    private AppCaptchaService captchaService;

    @Resource
    private FileService fileService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @GetMapping("/getCaptchaImage")
    @Operation(summary = "获取图形验证码")
    @PermitAll
    @Order(1) // 方法的顺序
    public CommonResult<CaptchaRespVO> getCode(HttpServletResponse response) throws IOException
    {
        return success(captchaService.getCaptcha());
    }

    @PostMapping("/sendSmsCodeRegister")
    @Operation(summary = "注册发送手机短信验证码")
    @PermitAll
    @Order(2) // 方法的顺序
    public CommonResult<Boolean> sendSmsCodeRegister(@RequestBody @Valid AppAuthSmsSendReqVO reqVO) {
        jkUserService.sendSmsCodeRegister(reqVO);
        return success(true);
    }


    @PostMapping("/registerUser")
    @Operation(summary = "个人创建用户")
    @PermitAll
    @Order(3) // 方法的顺序
    public CommonResult<AppAuthLoginRespVO> registerUser(@Valid @RequestBody RegisterUserReqVO VO) {
        // 校验验证码
        String userIp = getClientIP();
        SmsCodeUseReqDTO codeUseReqDTO = new SmsCodeUseReqDTO()
                .setCode(VO.getPhoneCode())
                .setScene(SmsSceneEnum.JK_REGISTER.getScene())
                .setMobile(VO.getMobile())
                .setUsedIp(userIp);

        // 校验验证码
//        smsCodeApi.useSmsCode(codeUseReqDTO);

        UserSaveReqVO userSaveReqVO = new UserSaveReqVO();
        BeanUtils.copyProperties(VO, userSaveReqVO);
        userSaveReqVO.setUserType(0);
        userSaveReqVO.setStatus(1);
        userSaveReqVO.setPassword(passwordEncoder.encode(VO.getPassword()));
        return success(jkUserService.createUser(userSaveReqVO));
    }



    @PostMapping("/registerCompanyUser")
    @Operation(summary = "机构创建用户")
    @Order(4) // 方法的顺序
    @PermitAll
    public CommonResult<AppAuthLoginRespVO> createUser(@Valid @RequestBody RegisterComplainReqVO VO) {
        // 校验验证码
        String userIp = getClientIP();
        SmsCodeUseReqDTO codeUseReqDTO = new SmsCodeUseReqDTO()
                .setCode(VO.getPhoneCode())
                .setScene(SmsSceneEnum.JK_REGISTER.getScene())
                .setMobile(VO.getMobile())
                .setUsedIp(userIp);

        // 校验验证码
//        smsCodeApi.useSmsCode(codeUseReqDTO);

        UserSaveReqVO userSaveReqVO = new UserSaveReqVO();
        BeanUtils.copyProperties(VO, userSaveReqVO);
        userSaveReqVO.setUserType(1);
        userSaveReqVO.setStatus(1);
        if (VO.getComplainCode() != null
        || VO.getComplainName() != null
        || VO.getComplainPic() != null
        || VO.getComplainAddress() != null) {
            userSaveReqVO.setReviewStatus(1);
        }
        userSaveReqVO.setPassword(passwordEncoder.encode(VO.getPassword()));
        return success(jkUserService.createUser(userSaveReqVO));
    }


    // ========== 短信登录相关 ==========

    @PostMapping("/upload")
    @Operation(summary = "上传文件")
    @PermitAll
    @Order(5) // 方法的顺序
    public CommonResult<String> uploadFile(AppFileUploadReqVO uploadReqVO) throws Exception {
        MultipartFile file = uploadReqVO.getFile();
        byte[] content = IoUtil.readBytes(file.getInputStream());
        return success(fileService.createFile(content, file.getOriginalFilename(),
                uploadReqVO.getDirectory(), file.getContentType()));
    }


    @PostMapping("/sendSmsCodePasswordReset")
    @Operation(summary = "找回密码发送手机短信验证码")
    @PermitAll
    @Order(6) // 方法的顺序
    public CommonResult<Boolean> sendSmsCodePasswordReset(@RequestBody @Valid AppAuthSmsSendReqVO reqVO) {
        jkUserService.sendSmsCodePasswordReset(reqVO);
        return success(true);
    }

    @PostMapping("/resetPassword")
    @Operation(summary = "找回密码 - 使用手机 + 短信验证码")
    @PermitAll
    @Order(7) // 方法的顺序
    public CommonResult<AppAuthLoginRespVO> resetPassword(@RequestBody @Valid AppResertPasswordReqVO reqVO) {
        AppAuthLoginRespVO appAuthLoginRespVO = jkUserService.resetPassword(reqVO);
        return success(appAuthLoginRespVO);
    }


    @PostMapping("/sendSmsCodeLogin")
    @Operation(summary = "登录发送手机短信验证码")
    @PermitAll
    @Order(8) // 方法的顺序
    public CommonResult<Boolean> sendSmsCodeLogin(@RequestBody @Valid AppAuthSmsSendReqVO reqVO) {
        jkUserService.sendSmsCodeLogin(reqVO);
        return success(true);
    }



    @PostMapping("/smsLogin")
    @Operation(summary = "使用手机 + 验证码登录")
    @PermitAll
    @Order(9) // 方法的顺序
    public CommonResult<AppAuthLoginRespVO> smsLogin(@RequestBody @Valid AppAuthSmsLoginReqVO reqVO) {
        return success(jkUserService.smsLogin(reqVO));
    }

    @PostMapping("/login")
    @Operation(summary = "使用用户名称 + 密码登录")
    @PermitAll
    @Order(10) // 方法的顺序
    public CommonResult<AppAuthLoginRespVO> login(@RequestBody @Valid AppAuthLoginReqVO reqVO) {
        return success(jkUserService.login(reqVO));
    }


    @GetMapping("/get")
    @Operation(summary = "获得供应商基本信息")
    @Order(11) // 方法的顺序
    public CommonResult<UserGetRespVO> getUserInfo() {
        JkUserDO DO = jkUserService.getUser(getLoginUserId());
        UserGetRespVO bean = BeanUtils.toBean(DO, UserGetRespVO.class);
        return success(bean);
    }



    @PostMapping("/updateUser")
    @Operation(summary = "更新个人用户信息")
    @Order(12) // 方法的顺序
    public CommonResult<Boolean> updateUser(@Valid @RequestBody UserUpdateReqVO VO) {
        UserSaveReqVO updateReqVO = new UserSaveReqVO();
        BeanUtils.copyProperties(VO, updateReqVO);
        updateReqVO.setId(getLoginUserId());
        jkUserService.updateUser(updateReqVO);
        return success(true);
    }

    @PostMapping("/updateCompanyUser")
    @Operation(summary = "更新机构用户信息")
    @Order(12) // 方法的顺序
    public CommonResult<Boolean> updateCompanyUser(@Valid @RequestBody ComplainUpdateReqVO VO) {
        UserSaveReqVO updateReqVO = new UserSaveReqVO();
        BeanUtils.copyProperties(VO, updateReqVO);
        updateReqVO.setId(getLoginUserId());
        jkUserService.updateUser(updateReqVO);
        return success(true);
    }


    @PostMapping("/updateUserReview")
    @Operation(summary = "个人用户提交审核")
    @Order(12) // 方法的顺序
    public CommonResult<Boolean> updateUserReview(@Valid @RequestBody UserUpdateReviewReqVO VO) {
        UserSaveReqVO updateReqVO = new UserSaveReqVO();
        BeanUtils.copyProperties(VO, updateReqVO);
        updateReqVO.setId(getLoginUserId());
        updateReqVO.setReviewStatus(1);
        jkUserService.updateUser(updateReqVO);
        return success(true);
    }

    @PostMapping("/updateCompanyUserReview")
    @Operation(summary = "机构用户提交审核")
    @Order(12) // 方法的顺序
    public CommonResult<Boolean> updateCompanyUserReview(@Valid @RequestBody ComplainUpdateReviewReqVO VO) {
        UserSaveReqVO updateReqVO = new UserSaveReqVO();
        BeanUtils.copyProperties(VO, updateReqVO);
        updateReqVO.setId(getLoginUserId());
        updateReqVO.setReviewStatus(1);
        jkUserService.updateUser(updateReqVO);
        return success(true);
    }



//
//
//    @PutMapping("/updateStatus")
//    @Operation(summary = "更新用户审核状态")
//    @PreAuthorize("@ss.hasPermission('jikong:user:update')")
//    public CommonResult<Boolean> updateStatus(@Valid @RequestBody UserStatusReqVO updateReqVO) {
//        UserSaveReqVO userSaveReqVO = new UserSaveReqVO();
//        BeanUtils.copyProperties(updateReqVO, userSaveReqVO);
//        jkUserService.updateUser(userSaveReqVO);
//        return success(true);
//    }


}
